<?php

//Alleen op te roepen vanuit joomla zelf
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.helper');
jimport('joomla.mail.helper');
require_once( JApplicationHelper::getPath( 'front_html' ) );
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.$option.DS.'tables');

switch( $task ) {
		case "displaycaptcha":
                displaycaptcha();
                break;
		case "sendemail":
                SendEmail($option);
                break;
        default:
                ShowContactForm($option);
                break;
}

function displaycaptcha()
{
	global $mainframe;
		
	$params = &JComponentHelper::getParams('com_alfcontact');
	$user = & JFactory::getUser();
	$captcha = $params->get('captcha');
	
	if (($captcha == 1) OR (($captcha == 2) AND (!$user->name)))               { 			
		$Ok = null;
		$mainframe->triggerEvent('onCaptcha_Display', array($Ok));
		if (!$Ok) {
			echo "<br/>Error displaying Captcha<br/>";
			}																																												
		} 
}
	
function CheckCaptcha()
{
		global $mainframe;
		
        $user = & JFactory::getUser();
		$params = &JComponentHelper::getParams('com_alfcontact');
		$captchatype     = $params->get('captchatype', 1);
		$privatekey      = $params->get('privatekey');
		$captcha 	 = $params->get('captcha');
		$response_field  = JRequest::getVar('recaptcha_response_field', '', 'post', 'string');				
		$challenge_field = JRequest::getVar('recaptcha_challenge_field', '', 'post', 'string');
		
		// not using captcha!
		if (($captcha == 0) OR (($captcha == 2) AND ($user->name))) {
			return true;
		}
		
		$return = false;
		if ($captchatype == 1) {
			$word = JRequest::getVar('word', false, '', 'CMD');
			$mainframe->triggerEvent('onCaptcha_confirm', array($word, &$return));
		}
		else {
			require_once('recaptchalib.php');
			$resp = recaptcha_check_answer ($privatekey,$_SERVER["REMOTE_ADDR"], $challenge_field, $response_field);
			if ($resp->is_valid) {
				$return = true;
			}
        }
		
		if ($return) {
			return true;
		} else { 
			return false; 
		}
}

function SendEmail($option)
{
      	global $mainframe;
			
		// get the parameters
		$params = &JComponentHelper::getParams('com_alfcontact');
		$verbose = $params->get('verbose', 1);
		$html = $params->get('htmlmail', 1);
		$site = $params->get('fromsite', 0);
		$max = $params->get('maxchars', '');
		$messagesend = $params->get('messagesend', 'Your message has been sent.');
		$sitename = $mainframe->getCfg('fromname');
		$siteaddress = $mainframe->getCfg('mailfrom');
		
		if ($html) {
			$sep  = "<BR>";
			$line = "<HR>";
		} else {
			$sep  = "\n";
			$line = "-------------------------------------------------------------------------------\n";
		}
						
				
		//Variable ophalen die verstuurd zijn via URL
        $name       = JRequest::getVar('name','');
        $email      = JRequest::getVar('email','');		
		$emailto_id = JRequest::getVar('emailto_id','');
        $subject    = JRequest::getVar('subject','');
        $message    = JRequest::getVar('message','');
		$copy       = JRequest::getVar('copy','');
		$extravalue = JRequest::getVar('extravalue','');
		
		//check the security measures
		if (!CheckCaptcha()) {
			JError::raiseWarning("0", JText::_('WRONG_CAPTCHA'));
			ShowContactForm($option, $name, $email, $emailto_id, $subject, $extravalue, $message);
			return false;
		}
		
		//check if all fields are filled, otherwise give errormessage
        if(!$name || !$email || !$emailto_id || !$subject || !$message)
        {
        	JError::raiseWarning("0", JText::_('NOTALLFILLED'));
            ShowContactForm($option);
            return;
        }
        
		//check if a valid emailaddress has been filled in
		if(!JMailHelper::isEmailAddress($email))
        {
            JError::raiseWarning("0", JText::_('INVALIDEMAILADDRESS'));
            ShowContactForm($option);
            return;
        }
		
		//check for maximum characters if applicable
		if($max && (strlen($message) > $max))
        {
            JError::raiseWarning("0", JText::_('TOOMANYCHARS'));
            ShowContactForm($option);
            return;
        }
				
        //get email address coresponding to ID number
		if ($emailto_id == '99')
		{
			$emailto = $mainframe->getCfg('mailfrom'); 
		}
		else
		{		
			$db = & JFactory::getDBO();
			$query = "SELECT * FROM #__alfcontact WHERE id =". $emailto_id;
		
			$db->setQuery( $query );
        	$rows      = $db->loadObjectList();
			$emailto   = $rows[0]->email;
			$prefix    = $rows[0]->prefix;
			$redirect  = $rows[0]->redirect;
			$extraname = $rows[0]->extra;
		
            //Adding prefix to subject
			$subject = $prefix.' '.$subject;
		}
		
		//Split multiple email addresses into an array
		$recipients = explode(';', $emailto);
				
		// Add information from extra field if applicable
		if ($extraname)
		{
			$extramsg = $extraname . ": " . $extravalue . $sep;
			$extramsg = $extramsg . $line;
			$message = $extramsg . $sep . $message;
		}
								
		// send copy if requested
		if ($copy)
		{
			$copySubject = JText::_('COPYOFMESSAGE').' '.$sitename ;
			
			$mail = JFactory::getMailer();
			$mail->addRecipient($email);
			$mail->setSender(array($siteaddress, $sitename));
			$mail->setSubject($copySubject);
			$mail->setBody($message);
			if ($html)
			{
				$mail->IsHTML(True);
				$mail->setBody(nl2br($message));
		    }
			$sent = $mail->Send();
		}
		
		//Add an infomation banner to the top of the contacts message.
		if ($verbose)
		{
			$header = JText::_('DETAILS_HEADER') . $sep;
			$header = $header . $line;
			$header = $header . JText::_('DETAILS_NAME') . " " . $name . $sep;
			$header = $header . JText::_('DETAILS_EMAIL') . " " . $email . $sep;
			$header = $header . JText::_('DETAILS_IP') . " " . $_SERVER['REMOTE_ADDR'] . $sep;
			$header = $header . JText::_('DETAILS_BROWSER') . " " .$_SERVER['HTTP_USER_AGENT'] . $sep;
			$header = $header . $line;
			$message  =  $header . $message; 
		}
		
		//send mail
		$mail = JFactory::getMailer();
		
		foreach($recipients as $value){
			$mail->addRecipient($value);	
		}
		
		if ($site){
			$mail->setSender(array($siteaddress, $name));
		}
		else {
			$mail->setSender(array($email, $name));
		}
				
		$mail->setSubject($subject);
		$mail->setBody($message);
		//test adding reply-to
		$mail->addReplyTo(array($email, $name));
		//
		if ($html) {
			$mail->IsHTML(True);
			$mail->setBody(nl2br($message));
		}
		$sent = $mail->Send();
		
		//redirect
		if (!$redirect) 
		{
			echo $messagesend; 
		}
		else
		{
			$link = JRoute::_($redirect);
			$mainframe->redirect($link);
		}
		
}       
        
function showContactForm($option)
{
        //Verbinding maken met database
        $db = & JFactory::getDBO();
		
        $user = & JFactory::getUser();
				
        /* SQL query of all published entries wich may be seen by current user*/        
		$aid = $user->GET('aid', 0);
		
		$query = "SELECT * FROM #__alfcontact WHERE published='1' AND access <=" . (int) $aid;
				
		$db->setQuery( $query );
        $rows = $db->loadObjectList();
        if ($db->getErrorNum())
                {
                        echo $db->stderr();
                        return false;
                }
                
        $name       = JRequest::getVar('name','');
		$email      = JRequest::getVar('email','');
		$emailto_id = JRequest::getVar('emailto_id','');
        $subject    = JRequest::getVar('subject','');
        $message    = JRequest::getVar('message','');
		$copy       = JRequest::getVar('copy','');
		$extravalue = JRequest::getVar('extravalue','');
        
		HTML_alfcontact::ShowContactForm($option, $name, $email, $emailto_id, $subject, $extravalue, $message, $rows);
		 
}
?>
